package cn.com.yinhex.controller;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


import cn.com.yinhex.as.util.ParamUtil;
import cn.com.yinhex.as.util.StringUtil;
import cn.com.yinhex.domain.User;
import cn.com.yinhex.service.UserService;
import cn.com.yinhex.util.Config;
import cn.com.yinhex.util.Pager;
@Controller
@RequestMapping("/user")
public class UserController{
	private static final Logger logger = Logger.getLogger(UserController.class);
	@Resource(name="userService")
	private UserService userService;
	
	@RequestMapping(value = "userinfo", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView userInfo(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		ModelAndView mav = new ModelAndView();
		System.out.println("user-info");
		mav.setViewName("userinfo");
		return mav;
	}
	@RequestMapping(value = "test", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView Test(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		ModelAndView mav = new ModelAndView();
		User user = new User();
		user.setAddress("123我的问题");
		user.setBirthday(new Date());
		user.setCreateUser("1233");
		user.setEmail("2121211221");
		user.setGrade(1);
		user.setBmDate(new Date());
		user.setImageURL("211221212");
		user.setLicense(1);
		user.setLocation("22112w我啊啊");
		user.setSex(1);
		user.setUserName("liuxuejin");
		user.setQq("595930708");
		user.setPassWord("123346587");
		user.setAllStr("iwoeioweuiwr");
		user.setClassnum("sdfdfdsf");
		user.setPtime(new Date());
		user.setPayment(3600);
		user.setTelephone("15013236903");
		user.setMailNum("526200");
		
		userService.addUser(user);
		mav.addObject("username","liuxuejin");
		System.out.println("user-info");
		mav.setViewName("userinfo");
		return mav;
	}
	@RequestMapping(value = "userList", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView userList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		ParamUtil pu = new ParamUtil(request);
		String  qq  = pu.getString("qq");
		int  pageNum = pu.getInt("pageNum");
		int  numPerPage = pu.getInt("numPerPage");
		System.out.println("===="+pageNum+numPerPage);
		String keyword = pu.getString("keyword");
		String  queryString = request.getQueryString();
		System.out.println("queryString=="+queryString);
		String[]  queryArrays = queryString.split("keyword=");
		if(queryArrays.length==1){
			keyword = "";
		}else{
			String str = queryArrays[1];
			keyword = URLDecoder.decode(str,"utf-8");
			
		}
		System.out.println("keyword==="+keyword);
		Pager pager = new Pager();
		 pageNum = 1;
		 numPerPage =10;
		pager.setPage(1);
		pager.setPageSize(10);
		List<User> userList = userService.getUserList(keyword, pager);
		mav.addObject("userList", userList);
		mav.addObject("totalCount", 15);
		mav.addObject("numPerPage", 10);
		mav.addObject("currentPage", 1);
		mav.setViewName("user/userList");
		return mav;
	}
	
	@RequestMapping(value = "addUser", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView addUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		System.out.println("addUser");
		ParamUtil pu  = new ParamUtil(request);
		
		String  userName = pu.getString("username");
		if(userName==null || "".equalsIgnoreCase(userName)){
			mav.setViewName("user/addUser");
			return mav;
			
		}
		
		String  email  = pu.getString("email");
		String  telephone = pu.getString("telephone");
		String  passWord  = pu.getString("password");
		String  ssid      = pu.getString("ssid");
		String birthday   =  pu.getString("birthday");
		String address    = pu.getString("address");
		int license    = pu.getInt("license");
		String  qq        = pu.getString("qq");
		int  sex       = pu.getInt("sex");
		int  grade     = pu.getInt("grade");
		String  location  = pu.getString("location");
		System.out.println("location===="+location);
		User user = new User();
		user.setEmail(email);
		user.setTelephone(telephone);
		user.setPassWord(passWord);
		user.setAddress(address);
		user.setQq(qq);
		user.setSex(sex);
		user.setSsid(ssid);
		user.setGrade(grade);
		user.setLicense(license);
		user.setCreateUser("admin");
		user.setLocation(location);
		user.setUserName(userName);
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		        // 获得文件：   
		MultipartFile file = multipartRequest.getFile("imageURL");   
		        // 获得文件名：
		String  parentDir = null;
		String filename = null;
		if(file.getSize()!=0){
			filename = file.getOriginalFilename();   
	        // 获得输入流：   
			InputStream input = file.getInputStream();   
	        // 写入文件  
			parentDir = request.getSession().getServletContext().getRealPath("/"); 
			System.out.println("parentDir==="+parentDir);
			System.out.println("filename==="+filename);
			OutputStream outputStream = new FileOutputStream(parentDir+"profile\\"+filename);
			byte[] buffer = file.getBytes();
			int bytesum = 0;
			int byteread = 0;
			while ((byteread = input.read(buffer)) != -1) {
			bytesum += byteread;
			outputStream.write(buffer, 0, byteread);
			outputStream.flush();
			}
			
		}
	    
		String imageURL= "/yinhex/"+"profile/"+filename;
		System.out.println("imageURL====="+imageURL);
		user.setImageURL(imageURL);
		userService.addUser(user);
		System.out.println("addUser");
		String msg = "<script>window.parent.showMsg()</script>";
        PrintWriter printer  = response.getWriter();
        printer.write(msg);
        printer.flush();
        printer.close();
        return null;
	}
	@RequestMapping(value = "useExcel", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView userExcel(HttpServletRequest request,
			HttpServletResponse respone) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("user/useExcel");
		return mav;
	}
	@RequestMapping(value = "delete", method = { RequestMethod.GET, RequestMethod.POST })
	public void delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ParamUtil  pu = new ParamUtil(request);
		
		String     userId = pu.getString("userid");
		System.out.println("userid===="+userId);
		userService.deleteUser(userId);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
	    jsonMap.put("statusCode", 200);
	    JSONObject jsonObject = JSONObject.fromObject(jsonMap);
	    response.setContentType("html/txt");
	    System.out.println("我是delete===user");
	    response.setCharacterEncoding("utf-8");
	    response.setHeader("Pragma", "no-cache");
	    response.setHeader("Cache-Control", "no-cache, must-revalidate");
	    response.setHeader("Pragma", "no-cache");
	    System.out.println(jsonObject.toString());
	    response.getWriter().write(jsonObject.toString());
	    response.getWriter().flush();
	    response.getWriter().close();
		
		
	}
	

}
